/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveWebServicesV12Helpers
{
	/// <summary>
	/// Interface providing access to bind services
	/// </summary>
	internal interface IBindServices
	{
		object BindToObject(ref string[] i_URLParts, int i_URLPartIndex);
		
		string BindableURL
		{
			get;
		}
	}

	/// <summary>
	/// Implements bind services
	/// </summary>
	public class BindServices
	{
		internal const string GWSH_PROTOCOL = "grooveWebServicesHelpers://";

		public static object Bind(string i_BindableURL)
		{
			return Bind
				(
				i_BindableURL, 
				new GrooveWebServicesV12Helpers.Context()
				);
		}

		public static object Bind(string i_BindableURL, GrooveWebServicesV12Helpers.Context i_Context)
		{
			if (!i_BindableURL.StartsWith(GWSH_PROTOCOL))
				throw new System.Exception("Invalid URL: '" + i_BindableURL + "'");

			object BindResult = null;
			string AccountURI;
			string[] URLParts = null;

			string RemainingURL = i_BindableURL.Substring(GWSH_PROTOCOL.Length);
			if (RemainingURL.IndexOf("/") != -1)
			{
				URLParts = RemainingURL.Split(new char[]{'/'});
				AccountURI = URLParts[0];
			}
			else
				AccountURI = RemainingURL;

			GrooveWebServicesV12Helpers.Account[] Accounts = GrooveWebServicesV12Helpers.Account.GetAccounts(i_Context);
			foreach (GrooveWebServicesV12Helpers.Account Account in Accounts)
			{
				if (Account.URI == AccountURI)
				{
					BindResult = Account;
					break;
				}
			}

			//  If there are more url parts, continue binding
			if (URLParts != null)
			{
				try
				{
					GrooveWebServicesV12Helpers.IBindServices IBindServices = (GrooveWebServicesV12Helpers.IBindServices)BindResult;
					BindResult = IBindServices.BindToObject(ref URLParts, 1);
				}
				catch (System.Exception Exception)
				{
					throw new System.Exception("Invalid URL: " + Exception.Message);
				}
			}

			return BindResult;
		}
	}
}
